<template>
  <div>
    <div style="margin: 10px 0px;font-size: 13px;">
      <span>{{$t('server.autoRefush')}}:</span>
      <el-switch v-model="autoRefush" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
    </div>
    <!--单机信息 -->
    <div v-if="!isCluster" class="redisInfo">
      <div class="server-info" v-if="info.Server">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-card class="box-card">
              <div slot="header" class="clearfix"><span class="el-icon-s-platform"></span>{{$t('server.server')}}</div>
                <div><el-tag effect="dark">{{$t('server.redis_version')}}：{{info.Server.redis_version}}</el-tag></div>
                <div><el-tag effect="dark" type="success">{{$t('server.os')}}：{{info.Server.os}}</el-tag></div>
                <div><el-tag effect="dark" type="info">{{$t('server.process_id')}}：{{info.Server.process_id}}</el-tag></div>
                <div><el-tag effect="dark" type="danger">{{$t('server.multiplexing_api')}}：{{info.Server.multiplexing_api}}</el-tag>
              </div>
              <div>
                <el-tag effect="dark" type="warning">{{$t('server.redis_mode')}}：{{info.Server.redis_mode}}</el-tag>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="box-card">
              <div slot="header" class="clearfix"><span class="el-icon-pie-chart"></span>{{$t('server.ram')}}</div>
              <div><el-tag effect="dark" type="warning">{{$t('server.mem_allocator')}}：{{info.Memory.mem_allocator}}</el-tag></div>
              <div><el-tag effect="dark" type="info">{{$t('server.used_memory_peak_human')}}：{{info.Memory.used_memory_peak_human}}</el-tag></div>
              <div><el-tag effect="dark" type="danger">{{$t('server.used_memory_human')}}：{{info.Memory.used_memory_human}}</el-tag></div>
              <div><el-tag effect="dark" type="success">{{$t('server.used_memory_lua')}}：{{info.Memory.used_memory_lua}}</el-tag></div>
              <div><el-tag effect="dark">{{$t('server.mem_fragmentation_ratio')}}：{{info.Memory.mem_fragmentation_ratio}}</el-tag></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="box-card">
              <div slot="header" class="clearfix"><span class="el-icon-odometer"></span>{{$t('server.status')}}</div>
              <div><el-tag effect="dark" type="success">{{$t('server.connected_clients')}}：{{info.Clients.connected_clients}}</el-tag></div>
              <div><el-tag effect="dark" type="danger">{{$t('server.total_commands_processed')}}：{{info.Stats.total_commands_processed}}</el-tag></div>
              <div><el-tag effect="dark" type="info">{{$t('server.instantaneous_ops_per_sec')}}：{{info.Stats.instantaneous_ops_per_sec}}</el-tag></div>
              <div><el-tag effect="dark" >{{$t('server.total_net_input_bytes')}}：{{info.Stats.total_net_input_bytes}}/byte</el-tag></div>
              <div><el-tag effect="dark" type="warning">{{$t('server.total_net_output_bytes')}}：{{info.Stats.total_net_output_bytes}}/byte</el-tag></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div class="key-summary">
        <el-card class="box-card">
          <div slot="header" class="clearfix">{{$t('server.Statistics')}}</div>
          <el-table :data="Db">
            <el-table-column prop="name" label="DB" sortable></el-table-column>
            <el-table-column prop="keys" label="Keys" sortable></el-table-column>
            <el-table-column prop="expires" label="Expires" sortable></el-table-column>
            <el-table-column prop="avg_ttl" label="avg_ttl" sortable></el-table-column>
          </el-table>
        </el-card>
      </div>
      <div class="server-config">
        <el-card class="box-card">
          <div slot="header" class="clearfix">{{$t('server.SysInfo')}}</div>
          <el-table :data="sysInfo">
            <el-table-column prop="key" label="key" sortable></el-table-column>
            <el-table-column prop="value" label="value" sortable></el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
    <!--集群信息 -->
    <div v-if="isCluster" class="clusterInfo">
        <div class="server-info">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-card class="box-card">
                  <div slot="header" class="clearfix"><span class="el-icon-s-platform"></span>{{$t('server.ClusterInfo')}}</div>
                  <div><el-tag effect="dark">{{$t('server.ClusterState')}}：{{clusterInfo.cluster_state}}</el-tag></div>
                  <div><el-tag effect="dark" type="success">{{$t('server.cluster_known_nodes')}}：{{clusterInfo.cluster_known_nodes}}</el-tag></div>
                  <div><el-tag effect="dark" type="danger">{{$t('server.cluster_size')}}：{{clusterInfo.cluster_size}}</el-tag></div>
                  <div><el-tag effect="dark" type="warning">{{$t('server.cluster_current_epoch')}}：{{clusterInfo.cluster_current_epoch}}</el-tag></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix"><span class="el-icon-pie-chart"></span>{{$t('server.slotsInfo')}}</div>
                  <div><el-tag effect="dark" type="warning">{{$t('server.cluster_slots_assigned')}}：{{clusterInfo.cluster_slots_assigned}}</el-tag></div>
                  <div><el-tag effect="dark" type="danger">{{$t('server.cluster_slots_ok')}}：{{clusterInfo.cluster_slots_ok}}</el-tag></div>
                  <div><el-tag effect="dark" type="success">{{$t('server.cluster_slots_pfail')}}：{{clusterInfo.cluster_slots_pfail}}</el-tag></div>
                  <div><el-tag effect="dark">{{$t('server.cluster_slots_fail')}}：{{clusterInfo.cluster_slots_fail}}</el-tag></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="box-card">
                <div slot="header" class="clearfix"><span class="el-icon-odometer"></span>{{$t('server.ClusterStatus')}}</div>
                <div><el-tag effect="dark" type="success">{{$t('server.cluster_stats_messages_sent')}}：{{clusterInfo.cluster_stats_messages_sent}}</el-tag></div>
                <div><el-tag effect="dark" type="warning">{{$t('server.cluster_stats_messages_received')}}：{{clusterInfo.cluster_stats_messages_received}}</el-tag></div>
                <div><el-tag effect="dark">{{$t('server.cluster_stats_messages_meet_received')}}：{{clusterInfo.cluster_stats_messages_meet_received}}</el-tag></div>
                <div><el-tag effect="dark" type="danger">{{$t('server.cluster_my_epoch')}}：{{clusterInfo.cluster_my_epoch}}</el-tag></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <div class="cluster-nodes">
          <el-card class="box-card">
            <div slot="header" class="clearfix">{{$t('server.nodeInfo')}}</div>
            <el-table :data="nodesInfo">
              <el-table-column prop="id" label="id"></el-table-column>
              <el-table-column prop="ip/port" label="ip/port"></el-table-column>
              <el-table-column prop="flags" label="flags"></el-table-column>
              <el-table-column prop="master" label="master"></el-table-column>
              <el-table-column prop="ping-sent" label="ping-sent"></el-table-column>
              <el-table-column prop="pong-recv" label="pong-recv"></el-table-column>
              <el-table-column prop="config-epoch" label="config-epoch"></el-table-column>
              <el-table-column prop="link-state" label="link-state"></el-table-column>
              <el-table-column prop="slot" label="slot"></el-table-column>
            </el-table>
          </el-card>
        </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ["data"],
  data() {
    return {
      isCluster:false,
      info: {},
      Db: [],
      sysInfo:[],
      clusterInfo:{},
      nodesInfo:[],
      autoRefush:false,
      timer:null
    };
  },
  created() {
    this.init();
  },
  methods: {
    //初始化
    init(){
      this.isCluster = this.data.redisClient.constructor.name === "Cluster";
      if(!this.isCluster){
        this.redisInfo();
      }else{
        this.culsterInfo();
      }
    },
    //单机redis初始化信息
    redisInfo(){
      this.data.redisClient.info().then(res => {
        let info = this.resolve(res);
        this.info=info;
        //对象转数组
        this.Db=Object.keys(info['Keyspace']).map(function(i){
          const data=info['Keyspace'][i].split(',');
          return {name:i,keys:data[0].split("=")[1],expires:data[1].split("=")[1],avg_ttl:data[2].split("=")[1]}
        })
        //对象转下层数组
        let sysInfo=Object.keys(info).map(function(i){
          return info[i]
        })
        var sysInfoArray=[]
        for(var item in sysInfo){
          let array=Object.keys(sysInfo[item]).map(function(i){
            return {key:i,value:sysInfo[item][i]}
          })
          sysInfoArray=sysInfoArray.concat(array)
        }
        this.sysInfo=sysInfoArray
      }).catch((e)=>{
        this.$message.error({
          message:e.message
        })
      })
    },
    //集群信息监测
    culsterInfo(){
      this.data.redisClient.cluster("info").then((res)=>{
        this.clusterInfo=this.clusterInfoResolve(res)
      })
      this.data.redisClient.cluster("nodes").then((res)=>{
        this.nodesInfo=this.clusterNodesResolve(res)
      })
    },
    //解析Info返回值
    resolve(content) {
      var result={};
      var resolveData=content.split("\r\n")
      var key="";
      var value={};
      for(var i=0;i<resolveData.length;i++){
        if(resolveData[i].indexOf('#')>=0 || resolveData[i].indexOf(":")<0){
            key=resolveData[i].replace('# ','');
            value={};
        }else{
            var k=resolveData[i].split(":")[0]
            var v=resolveData[i].split(":")[1]
            value[k]=v;
            result[key]=value;
        }
      }
      return result;
    },
    //集群信息解析
    clusterInfoResolve(content){
      var result={};
      var resolveData=content.split("\r\n")
      for(var i=0;i<resolveData.length;i++){
        let item=resolveData[i].split(":")
        if(item[1]===undefined){
          continue
        }
        result[item[0]]=item[1]
      }
      return result;
    },
    //集群节点信息
    clusterNodesResolve(content){
      let nodeArray=[]
      var resolveData=content.split("\n")
      for(var i=0;i<resolveData.length;i++){
        if(resolveData[i]===""){
          continue;
        }
        let item=resolveData[i].split(" ")
        let arrayItem={'id':item[0],'ip/port':item[1],'flags':item[2],'master':item[3],'ping-sent':item[4],'pong-recv':item[5],'config-epoch':item[6],'link-state':item[7],'slot':item[8]}
        nodeArray.push(arrayItem)
      }
      return nodeArray;
    }
  },
  watch:{
    //监测
    autoRefush(newValue,oldValue){
      if(newValue){
        this.timer=setInterval(()=>{this.init()},3000)
      }else{
        clearInterval(this.timer)
      }
    }
  }
};
</script>

<style scoped>
.key-summary,.cluster-nodes {
  margin: 15px 0px;
}
.server-info >>> .el-card__body {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 12px;
  line-height: 35px;
}
</style>